package com.wurd.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.wurd.test.config.Config;
import com.wurd.test.exception.WxException;
import com.wurd.test.wx.utils.TokenUtils;
import com.wurd.test.wx.token.Cache;
import com.wurd.test.wx.token.Token;
import com.wurd.test.wx.token.TokenBuilder;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@RestController
@RequestMapping("/wx/gzh")
public class WxGzhController {

    @Autowired
    private Cache cache;

    @Autowired
    private TokenBuilder tokenBuilder;

    @GetMapping(value = "/industry/set")
    public Object setIndustry(HttpServletRequest request) {
        try {
            System.out.println("industry/set");
            JSONObject preParam = new JSONObject();
            Token token = cache.getGzhAccessToken();
            if (!TokenUtils.verifyToken(token)) {
                return "token不存在或者过期";
            }
            preParam.put("access_token", token.getToken());
            JSONObject preBody = new JSONObject();
            request.getParameterMap().forEach((k, v) -> {
                preParam.put(k, v[0]);
            });
            JSONObject obj = TokenUtils.postGzhIndustry(preParam, preBody);
            return obj;
        } catch (WxException e) {
            e.printStackTrace();
            return e.getMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping(value = "/industry/get")
    public Object getIndustry() {
        try {
            System.out.println("industry/get");
            Token token = cache.getGzhAccessToken();
            if (!TokenUtils.verifyToken(token)) {
                return "token不存在或者过期";
            }
            JSONObject preParam = new JSONObject();
            preParam.put("access_token", token.getToken());
            JSONObject obj = TokenUtils.getGzhIndustry(preParam);
            return obj;
        } catch (WxException e) {
            e.printStackTrace();
            return e.getMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping(value = "/accessToken")
    public Object accessToken() {
        try {
            System.out.println("accessToken");
            JSONObject preParam = new JSONObject();
            preParam.put("grant_type", "client_credential");
            preParam.put("appid", Config.gzh_appid);
            preParam.put("secret", Config.gzh_appSecret);
            JSONObject obj = TokenUtils.getGzhAccessToken(preParam);
            long createTs = System.currentTimeMillis() / 1000;
            cache.setGzhAccessToken(tokenBuilder.buildToken(
                    obj.getString("access_token"), createTs, obj.getLongValue("expires_in")));
            return obj;
        } catch (WxException e) {
            e.printStackTrace();
            return e.getMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping(value = "/token")
    public String token(HttpServletRequest request) {
        System.out.println("token");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        if (checkSignature(signature, timestamp, nonce)) {
            String echoStr = request.getParameter("echostr");
            return echoStr;
        }
        return null;
    }

    public boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[]{Config.gzh_token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = new String(Hex.encodeHex(digest, false));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return tmpStr != null && tmpStr.equalsIgnoreCase(signature);
    }

}
